package clientTcp

import (
	"core/command"
	"core/common"
	"core/component/logger"
	"core/network"
	"math/rand"
	"net"
	"strconv"
	"sync"
	"time"
)

type TcpClientRobot struct {
	tcpClient *network.TcpClient
	onMsg     sync.Once
}

func RunClientTcp() {
	resp := &common.GetAllServerInfoResp{}
	if err := common.SendCenterHttpRequest(nil, resp, "GET", "/getAllTcpServer"); err != nil {
		return
	}
	for i := 85000; i < 85001; i++ {
		tcpAddr, err := net.ResolveTCPAddr("tcp", resp.SInfos[rand.Intn(len(resp.SInfos))].Addr)
		if err != nil {
			return
		}
		tcR := &TcpClientRobot{
			tcpClient: network.NewTcpClient(1024, 1024),
		}
		tcR.tcpClient.Connect(tcpAddr.String())
		tcR.onMsg.Do(tcR.Register)
		go tcR.add(i)
	}
}

func (tcR *TcpClientRobot) Register() {
	tcR.tcpClient.Router.Register(uint16(command.Command_SCPlayerLoginInfo_Gateway), tcR.loginSuccess)
	tcR.tcpClient.Router.Register(uint16(command.Command_SCRandNickName_Online), tcR.scRandName)
	tcR.tcpClient.Router.Register(uint16(command.Command_SCSetNickName_Online), tcR.scSetName)
}

func (tcR *TcpClientRobot) scSetName(msgID uint16, data []byte) {
	logger.Info("scSetName")
	time.Sleep(5 * time.Second)
	msg3 := &command.CSStartPvp{}
	tcR.sendMsg(command.Command_CSStartPvp_Pvp, msg3)
}

func (tcR *TcpClientRobot) scRandName(msgID uint16, data []byte) {
	logger.Info("scRandName")
	msgRecv := &command.SCRandNickName{}
	err := tcR.tcpClient.Router.UnMarshal(data, msgRecv)
	if err != nil {
		logger.Errorf("recv data:%v msg:%v", data, msgRecv)
		return
	}
	if msgRecv.Name != "" {
		time.Sleep(30 * time.Millisecond)
		msg2 := &command.CSSetNickName{NickName: msgRecv.Name}
		tcR.sendMsg(command.Command_CSSetNickName_Online, msg2)
	} else {
		time.Sleep(5 * time.Second)
		msg3 := &command.CSStartPvp{}
		tcR.sendMsg(command.Command_CSStartPvp_Pvp, msg3)
	}
}

func (tcR *TcpClientRobot) loginSuccess(msgID uint16, data []byte) {
	logger.Info("loginSuccess")
	msg3 := &command.CSRandNickName{}
	tcR.sendMsg(command.Command_CSRandNickName_Online, msg3)
}

func (tcR *TcpClientRobot) add(account int) {
	logger.Infof("account:%v", account)

	msg1 := &command.CSPlayerLogin{Account: strconv.Itoa(account), Password: "00000"}
	tcR.sendMsg(command.Command_CSPlayerLogin_Gateway, msg1)
	//time.Sleep(5 * time.Second)
	//msg2 := &command.CSPlayerLogout{}
	//sendMsg(client, command.Command_CSPlayerLogout_Gateway, msg2)

	//msg3 := &command.CSStartPvp{}
	//sendMsg(tcR.tcpClient, command.Command_CSStartPvp_Pvp, msg3)
	//msgSend_2 := &command.CSPlayerLogin{}
	//ch <- sendMsg(command.Command_CSPlayerLogin_Gateway, msgSend_2)
	//time.Sleep(3 * time.Second)
	//
	//msgSend_3 := &command.CSJoinPvpPoolPvp{}
	//ch <- sendMsg(command.Command_CSJoinPvpPool_Pvp, msgSend_3)

}

// sendMsg 异步发送数据包
func (tR *TcpClientRobot) sendMsg(cmd command.Command, msg interface{}) bool {
	return tR.tcpClient.AsyncSend(uint16(cmd), msg)
}
